#include "Sock.hpp"
#include<unistd.h>
void Usage(std::string proc)
{
  cout <<"Usage:\t" <<proc <<" port" << endl;
}

#define MAX_FD (sizeof(fd_set)*8)
#define INVALID_FD -1
int main(int argc,char* argv[])
{
  if(argc != 2)
  {
    Usage(argv[0]);
    exit(1);
  }
  uint16_t port = atoi(argv[1]);
  int listen_sock = Sock::Socket();
  Sock::Bind(listen_sock,port);
  Sock::Listen(listen_sock);
  
  int read_array[MAX_FD];
  read_array[0] = listen_sock;
  for(int i = 1;i<(int)MAX_FD;i++) read_array[i] = INVALID_FD;
  
  while(1)
  {
    fd_set rfds;
    FD_ZERO(&rfds);
    int max_fd = read_array[0];
    for(int i = 0;i<(int)MAX_FD;i++)
    {
      if(read_array[i] != INVALID_FD)
        FD_SET(read_array[i],&rfds),max_fd = max(max_fd,read_array[i]); 
    }
    struct timeval t;
    t.tv_sec =5;
    int n = select(max_fd+1,&rfds,nullptr,nullptr,nullptr);
    cout <<"????" << endl;
    switch(n)
    {
      case -1:
        LOG(WARMING) <<"select调用失败" << endl;
        break;
      case 0:
        LOG(NORMAL) <<"select超时返回" << endl;
        break;
      default:
        LOG(NORMAL) <<"有文件描述符就绪啦,就绪的个数为:" << n << endl;
        for(int i = 0;i<(int)MAX_FD;i++)
        {
          if(__FD_ISSET(read_array[i],&rfds))
          {
            if(read_array[i] == listen_sock)
            {
              LOG(NORMAL) <<"监听套接字读事件就绪" << endl;
              int new_sock = Sock::Accept(listen_sock);
              
              int pos = 1; //不应该从i位置开始！因为可能前面位置的要关心的fd已经关闭连接
              for(;pos<(int)MAX_FD;pos++)
              {
                if(read_array[pos] == INVALID_FD) 
                {
                  LOG(NORMAL) <<"新连接被放到了:"<<pos <<"位置" << endl; 
                  read_array[pos] = new_sock;
                  break;
                }
              } 
              if(pos >= (int)MAX_FD) 
              {
                LOG(WARMING) <<"服务器已经满载！不能再提供服务" << endl;
                close(new_sock);
              }
            }
            else 
            {
                LOG(NORMAL) <<"普通文件描述符: "<<read_array[i] <<"读事件就绪" << endl;
                char buf[1024] = {0};
                ssize_t n = read(read_array[i],buf,sizeof(buf)-1);
                if(n >0)
                {
                  buf[n] = 0; 
                  LOG(NORMAL) <<"fd:" <<read_array[i] <<"发来数据:" << buf << endl;
                }
                else 
                {
                  LOG(WARMING) <<"从fd:" << read_array[i]<<"读取数据出错！" << endl;
                  LOG(NORMAL) <<read_array[i] <<"从数组当中移除,所在位置为:" << i  <<"连接关闭.." << endl;
                  read_array[i] = INVALID_FD;
                  close(read_array[i]);
                }
            }
          }
        }
        break;
    }
  }

  return 0;
}
